'use strict';

const BaseModel = require('./BaseModel');

/**
 * 菜单 表信息
 */
class SysMenusModel extends BaseModel {

  constructor() {
    super('sys_menus', 'id');
    this.entity = class entity {
      constructor() {
        this.id = null;
        this.name = null;
        this.type = null;
        this.parentId = null;
        this.controller = null;
        this.functionName = null;
        this.iconCode = null;
        this.sortIndex = null;
        this.remarks = null;
        this.creator = null;
        this.createTime = null;
        this.updateTime = null;
        this.rightsTypes = null;
        this.isRights = null;
        this.defaultRightsType = null;
      }
    };
  }

  async selectAllSysMenusList(app) {

    const sql = `select id,name,type,parent_id,controller,icon_code,sort_index,remarks,function_name,rights_types,is_rights from ${this.tableName} order by sort_index`;

    // 查询所有菜单数据
    // const results = await app.mysql.select(this.tableName, {
    //   columns: [ 'id', 'name', 'type', 'parent_id', 'controller', 'icon_code', 'sort_index', 'remarks', 'function_name' ],
    // });
    const results = await app.mysql.query(sql);

    if (results && results.length > 0) {
      const sysMenusList = [];
      for (const sysMenu of results) {
        let entity = new this.entity();
        entity = this.transformation_Entity(sysMenu);
        sysMenusList.push(entity);
      }
      return sysMenusList;
    }
    return null;
  }

  async selectUserAuthoListByAdminUserId(app, adminUserId, column) {
    const dbColumn = this.parseDBName(column);
    const sql = `select ${dbColumn} from sys_menus where id in
    (
      select menu_id from admin_role_menu_rel where role_id = 
      (
        select role_id from admin_user_role_rel where admin_user_id = '${adminUserId}' and type = 3
      )
    )`;
    // app.logger.debug('SQL:', sql);
    const results = await app.mysql.query(sql);

    if (results && results.length > 0) {
      const sysMenusList = [];
      for (const sysMenu of results) {
        let entity = new this.entity();
        entity = this.transformation_Entity(sysMenu);
        sysMenusList.push(entity[column]);
      }
      return sysMenusList;
    }
    return null;
  }

  async selectMenusListByRoleId(app, roleId) {
    // const sql = `select m.id, m.name, m.controller, m.rights_types,IFNULL(default_rights_type,'-1') as default_rights_type from sys_menus as m INNER JOIN admin_role_menu_rel as amr on m.id = amr.menu_id where m.type = 3 and amr.role_id = ${roleId} and m.is_rights = 1 `;
    // 优化菜单名称显示，增加父类名称
    const sql = `select 
              t.id,
              CONCAT('【',em.name ,'】',t.name) as name,
              t.controller,
              t.rights_types,
              t.default_rights_type
              
              from (
            select m.id,m.parent_id, m.name, m.controller, m.rights_types,IFNULL(default_rights_type,'-1') as default_rights_type
            from sys_menus as m INNER JOIN admin_role_menu_rel as amr on m.id = amr.menu_id
            where m.type = 3 and amr.role_id = ${roleId} and m.is_rights = 1
            ) as t LEFT JOIN sys_menus as em on t.parent_id = em.id 
            `;

    app.logger.debug('SQL:', sql);

    const results = await app.mysql.query(sql);

    if (results && results.length > 0) {
      const sysMenusList = [];
      for (const sysMenu of results) {
        let entity = new this.entity();
        entity = this.transformation_Entity(sysMenu);
        sysMenusList.push(entity);
      }
      return sysMenusList;
    }
    return null;
  }

  async selectMenuIdListByRoleId(app, roleId) {
    const sql = `select menu_id from admin_role_menu_rel where role_id = ${roleId}`;
    app.logger.debug('SQL:', sql);
    const results = await app.mysql.query(sql);

    if (results && results.length > 0) {
      const sysMenusList = [];
      for (const sysMenu of results) {
        let entity = new this.entity();
        entity = this.transformation_Entity(sysMenu);
        sysMenusList.push(entity.menuId);
      }
      return sysMenusList;
    }
    return null;
  }

  async selectAllSysMenusListByAdminUserId(app, adminUserId) {

    const sql = `select id,name,type,parent_id,controller,icon_code,sort_index,remarks from sys_menus where id in
    (
      select menu_id from admin_role_menu_rel where role_id = 
      (
        select role_id from admin_user_role_rel where admin_user_id = '${adminUserId}' and type != 3
      )
    ) order by sort_index `;
    app.logger.debug('SQL:', sql);
    const results = await app.mysql.query(sql);
    if (results && results.length > 0) {
      const sysMenusList = [];
      for (const sysMenu of results) {
        let entity = new this.entity();
        entity = this.transformation_Entity(sysMenu);
        sysMenusList.push(entity);
      }
      return sysMenusList;
    }
    return null;
  }

  // 菜单详情
  async findMenuByController(app, controller) {
    const sql = `select * from sys_menus where controller = '${controller}' `;
    const result = await app.mysql.query(sql);
    const menu = this.transformation_Entity(result[0] || '');
    return menu;
  }

  // 菜单详情
  async findAllMenuForIsRights(app, path, controller) {
    let sql = `select * from sys_menus where is_rights = 1 and function_name like '%${path}%' `;
    if (controller) {
      sql += ` and controller = '${controller}' `;
    }
    const results = await app.mysql.query(sql);
    if (results && results.length > 0) {
      const sysMenusList = [];
      for (const sysMenu of results) {
        let entity = new this.entity();
        entity = this.transformation_Entity(sysMenu);
        sysMenusList.push(entity);
      }
      return sysMenusList;
    }
    return null;
  }

  // 菜单详情
  async findMenuById(app, id) {
    const sql = `select * from sys_menus where id =${id}`;
    const result = await app.mysql.query(sql);
    const menu = this.transformation_Entity(result[0] || '');
    return menu;
  }

  async getMenuFunctionIndex(app) {
    const sql = 'select _nextval(\'functionIndex\') as fnIndex ';
    const result = await app.mysql.query(sql);
    return result[0].fnIndex;
  }

  // 添加菜单
  async adminAddMenu(app, menuModel) {
    const dbMenuModel = this.transformation_DBEntity(menuModel);
    return await app.mysql.insert('sys_menus', dbMenuModel);
  }

  // 删除菜单
  async deleteMenu(app, ids) {
    const sql = `delete from sys_menus where id in ${ids} `;
    return await app.mysql.query(sql);
  }

}

module.exports = SysMenusModel;